package com.zzyl.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;

import com.zzyl.service.MemService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class MemberServiceImpl implements MemService {

    @Autowired
    private WechatService webschatService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList<String> DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝",
            "大树立业"
    );
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1、根据code授权码，调用微信接口，获取openid【即用户的微信号id】
        String openid = webschatService.getOpenid(userLoginRequestDto.getCode());
log.info("code:{}",userLoginRequestDto.getCode());
        //2、根据openId查询用户信息
        Member member = memberMapper.getByOpenId(openid);

        //3、判断用户是否存在，不存在则创建用户对象，并赋值openId
        if(member == null){
            member = new Member();
            member.setOpenId(openid);
        }
log.info("获取的手机code：{}",userLoginRequestDto.getPhoneCode());
        //4、根据phoneCode授权码，调用微信接口，获取手机号
        String phone = webschatService.getPhone(userLoginRequestDto.getPhoneCode());
        member.setPhone(phone);
        //5、更新或保存用户信息
        String nickName = DEFAULT_NICKNAME_PREFIX.get( RandomUtil.randomInt(DEFAULT_NICKNAME_PREFIX.size())  );
        if(member.getId() == null){
            member.setName(nickName);
            memberMapper.save(member);
        }else {
            memberMapper.update(member);
        }

        //6、生成token令牌，并返回
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName( member.getName() );


        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());

        String jwt = JwtUtil.createJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(), // 密钥
                jwtTokenManagerProperties.getTtl(), // 过期时间
                claims  //载荷
        );
        loginVo.setToken(jwt);
        return loginVo;
    }
}
